<?php
class BallotsController extends AppController {

	var $name = 'Ballots';
	var $helpers = array('Html', 'Form');
	
	function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->allow('getBallot', 'view', 'setAttitude');
		$this->Auth->authError = "You need to login to use this feature.";
	}

	function index() {
		//$this->Ballot->findAllByUser_id($this->Session->read('Auth.User.id'));
		$this->Ballot->recrusive = 0;
		$this->set('ballots', $this->paginate(array('Ballot.user_id' => $this->Session->read('Auth.User.id'))));
	}

	function select($id) {
    //$this->Auth->autoRedirect = false;
		$this->view($id);
		$this->redirect(array('controller' => 'pages', 'action' => 'display', 'search'));
	}
	
	public function getBallot() {
		App::import('Vendor', 'VoteSmartBallot');
		if (!empty($this->data)) {
			$zip = $this->data['Ballot']['zip'];
			$plus4 = $this->data['Ballot']['plus4'];
		}
		if ($zip) {
			$this->Session->delete('ballotData');
			try{
				$ballot = new VoteSmartBallot($zip, $plus4);
				$ballot->makeBallot();
				$ballotData = $ballot->getBallot();
				$user_id = $this->Session->read('Auth.User.id');
        $savedData = $this->Ballot->findSavedBallot($user_id, 
                          $zip, $plus4, $ballotData['voteDate']);
        if (!empty($savedData)) {
        	$ballotData = unserialize($savedData['Ballot']['ballot_data']);
          $this->Session->setFlash(__("Saved ballot found. $user_id, 
                          $zip, $plus4, $ballotData[voteDate]", true));
        }
        else {
        	$this->Ballot->saveBallotData($this->Session->read('Auth.User.id'), $ballotData);
        }
	      $this->Session->write('ballotData', $ballotData);
			} catch(NoBallotException $nbe) {
				$this->Session->setFlash(__('No Ballot Found.', true));
			} catch(NeedPlusFourException $npfe) {
				$this->Session->setFlash(__('Need Plus Four.', true));
			}
		}
		else {
      $this->Session->setFlash(__('Zip code cannot be empty.', true));
		}
    $this->redirect($this->referer());
	}
	

	function view($id = null) {
		if ($id) {
			if ($this->Session->check('Auth.User')) {
	      $ballot = $this->Ballot->readBallotData($id);
	      if ($this->Session->read('Auth.User.id') == $ballot['Ballot']['user_id']) {
	        $ballotData = $ballot['Ballot']['ballot_data'];
	        $this->Session->write('ballotData', $ballotData);
          $this->Session->write('ballotId', $ballotData);
	        $this->set('ballot_id', $ballot['Ballot']['id']);
	        $this->set('ballotData', $ballotData);
	      }
	      else {
	        $this->Session->setFlash(__('You do not have access to this ballot.', true));
	      }
			}
			else {
        $this->Session->setFlash(__('You need to login to see saved ballot.', true));
			}
		}
		else {
      if ($this->Session->check('ballotData')) {
        $this->set('ballotData', $this->Session->read('ballotData'));
      }
      else if ($this->Session->check('Auth.User')) {
      	$ballot = $this->Ballot->findLastestBallot($this->Session->read('Auth.User.id'));
      	if (!empty($ballot)) {
          $ballotData = $ballot['Ballot']['ballot_data'];
          $this->Session->write('ballotData', $ballotData);
          $this->Session->write('ballotId', $ballot['Ballot']['id']);
          $this->set('ballot_id', $ballot['Ballot']['id']);
          $this->set('ballotData', $ballotData);
      	}
      }
		}
		
	}

	function save() {
		
    if ($this->Session->check('ballotData')) {
			if ($newId = $this->Ballot->saveBallotData($this->Session->read('Auth.User.id'), 
			$this->Session->read('ballotData')) > 0) {
				$this->Session->write('ballot_id', $newId);
				$this->Session->setFlash(__('The Ballot has been saved.', true));
			} else {
				$this->Session->setFlash(__('The Ballot could not be saved. Please, try again.', true));
			}
    }
		$this->redirect(array('action'=>'view'));
	}
	
	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Ballot', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Ballot->del($id)) {
			$this->Session->setFlash(__('Ballot deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}
	
  function setAttitude($attitude, $firstName, $lastName) {
  	switch ($attitude) {
      case 'dislike':
        $attd = false;
        break;
  		case 'like':
  			$attd = true;
  			break;
      case 'neutral':
        $attd = null;
        break;
      default:
      	trigger_error("Invalide attitude: $attitude. Should be 'like', 'dislike' or 'neutral'.");
      	return;
  	}
    if ($this->Session->check('ballotData')) {
    	$this->layout = 'ajax';
      $ballotData = $this->Session->read('ballotData');
      foreach ($ballotData['elections'] as &$election){
        foreach ($election['offices'] as &$office) {
          foreach ($office['candidates'] as &$candidate) {
            if (strcmp($candidate['firstName'], $firstName) == 0 && 
                strcmp($candidate['lastName'], $lastName) == 0) {
                  $candidate['like'] = $attd;
                  $this->Session->write('ballotData', $ballotData);
                if ($this->Session->check('Auth.User')) {
                  $id = $this->Ballot->saveBallotData($this->Session->read('Auth.User.id'), $ballotData);
                  if ($id > 0) {
                  	$this->Session->write('ballot_id', $id);
                  }
                }
                $this->set('attitude', $attd);
                $this->set('firstName', $firstName);
                $this->set('lastName', $lastName);
            }
          }
        }
      }
    }
  }

}
?>